package evs1.restframework;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.criterion.CriteriaSpecification;
import org.hibernate.criterion.Example;

import evs1.restframework.anno.Evs11Search;
import evs1.restframework.util.InitSessionFactory;

public class HibernateConnector 
{
	public HibernateConnector()
	{				
		
	}
	
	public Object getFromHibernate(Class<?> entity, long id) 
	{
		SessionFactory sf = InitSessionFactory.getSessionFactory();
		try {
			Session session = sf.getCurrentSession();
			Transaction t = session.beginTransaction();
			Object obj = session.get(entity, id);
			t.commit();
			return obj;
			//session.close();
		}catch (Exception e)
      {
         e.printStackTrace();
         return null;
      }							
	}
	
	public boolean postToHibernate(Object obj)
	{
		SessionFactory sf = InitSessionFactory.getSessionFactory();
		try {
			Session session = sf.getCurrentSession();
			Transaction t = session.beginTransaction();
			session.save(obj);
			t.commit();
			return true;
			//session.close();
		}catch (Exception e)
      {
         e.printStackTrace();
         return false;
      }
	}
	
	public boolean putToHibernate(Class<?> entity, Object obj, Long id)
	{
		SessionFactory sf = InitSessionFactory.getSessionFactory();
		try {
			Session session = sf.getCurrentSession();
			Transaction t = session.beginTransaction();		

			// load object with specified id. check if object exists
			Object objNew = session.get(entity, id);
			if(objNew == null)
				return false; 
			
			Field[] declaredFields = entity.getDeclaredFields();
			Field.setAccessible(declaredFields, true);
			
			// change all values (except id) of destination object to the values of the passed object
			for(int i = 0; i < declaredFields.length; i++)
			{
				if(declaredFields[i].get(obj) != null && declaredFields[i].equals(id) == false)
					declaredFields[i].set(objNew, declaredFields[i].get(obj));				
			}
			
			session.update(objNew);
			t.commit();
			return true;
			//session.close();
		}catch (Exception e)
      {
         e.printStackTrace();
         return false;
      }
	}
	
	public boolean deleteFromHibernate(Class<?> entity, Long id)
	{
		SessionFactory sf = InitSessionFactory.getSessionFactory();
		try {
			Session session = sf.getCurrentSession();
			Transaction t = session.beginTransaction();
			// load object from db and remove it
			Object obj = session.get(entity, id);
			if(obj == null)
				return false;
			session.delete(obj);
			t.commit();
			return true;
			//session.close();
		}catch (Exception e)
      {
         e.printStackTrace();
         return false;
      }
	}
	
	public List<Object> searchObject(Class<?> entity, Object obj)
	{
		List<Object> objects;
		SessionFactory sf = InitSessionFactory.getSessionFactory();
		try {		    
			Session session = sf.getCurrentSession();
			Transaction t = session.beginTransaction();
			/**
			 * The class org.hibernate.criterion.Example allows you to construct a query criterion from a given instance.
			 * http://docs.jboss.org/hibernate/core/3.5/reference/en/html/querycriteria.html 
			 */
			objects = (List<Object>)session.createCriteria(entity)
				.add(Example.create(obj))
				.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY)
				.list();
			t.commit();
			return objects;
		} catch (Exception e) {
		    e.printStackTrace();		    
		    return null;
		}
	}
	
	public List<Object> searchString(Class<?> entity, String searchStr, Field[] searchableFields)
	{
		List<Object> objects = new ArrayList<Object>();
		SessionFactory sf = InitSessionFactory.getSessionFactory();
		try {		    
			Session session = sf.getCurrentSession();
			Transaction t = session.beginTransaction();			
			
			// load all objects from db, then check their fields
			Field.setAccessible(searchableFields, true);
			Iterator<Object> it = (Iterator<Object>)session.createCriteria(entity)				
				.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY)
				.list()
				.iterator();
			t.commit();
			while(it.hasNext())
			{
				Object obj = it.next();
				for(int i = 0; i < searchableFields.length; i++)
				{								
					if(searchableFields[i].get(obj) == null)
						continue;
					if(((String)searchableFields[i].get(obj)).contains(searchStr))
					{
						objects.add(obj);
						break;
					}
				}
			}		
			return objects;
		} catch (Exception e) {
		    e.printStackTrace();		    
		    return null;
		}
	}
}